package project.dade.cn.bst.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;
import cn.bingoogolapple.bgabanner.BGABanner;
import project.dade.cn.bst.R;
import project.dade.cn.bst.adapter.base.ShoppingCartBean;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.ProderBanner;
import project.dade.cn.bst.model.ProderRequestModel;
import project.dade.cn.bst.model.ProderRequestModels;
import project.dade.cn.bst.model.ShopModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;


/**
 * Created by vain zhou on 2015/10/29.
 */
public class ProductDtailActivity extends ZJPBaseBarActivity implements View.OnClickListener,BGABanner.Adapter {
    public static String TAG = ProductDtailActivity.class.getSimpleName();
    @InjectView(R.id.backdrop)
    public BGABanner mDefaultBanner;
    @InjectView(R.id.errorLayout)
    EmptyLayout mErrorLayout;
    private String product;
    //轮播图数据
    ArrayList<ProderBanner> bannerLists;
    //轮播图集合
    private List<View> mDepthViews;
    @InjectView(R.id.productNameTv)
    TextView productname;
    @InjectView(R.id.productSellPrice)
    TextView Sell;
    @InjectView(R.id.productMarketPrice)
    TextView Market;
    @InjectView(R.id.detailSale)
    TextView Sale;
    @InjectView(R.id.productStockTv)
    TextView Stock;
    @InjectView(R.id.collection)
    CheckBox Collection;
    private String id;
    @InjectView(R.id.productNumSub)
    Button numBtn;
    @InjectView(R.id.productNumAdd)
    Button addBtn;
    @InjectView(R.id.productNum)
    EditText productNumTv;
    @InjectView(R.id.product_addShopcartBtn)
    Button ShopcartBtn;
    @InjectView(R.id.product_toBuyBtn)
    Button toBuyBtn;
    @InjectView(R.id.productComment)
    RelativeLayout productcomment;
    @InjectView(R.id.productImageTextRL)
    RelativeLayout productImage;
    private String productSales = "0"; // 产品库存
    private KProgressHUD hud;
    private   ProderRequestModel proderRequestModel;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_producatail);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_menu_arrow_back_white);
        setSupportActionBar(toolbar);
        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitleEnabled(false);
        initData();
        addBtn.setOnClickListener(this);
        numBtn.setOnClickListener(this);
        ShopcartBtn.setOnClickListener(this);
        toBuyBtn.setOnClickListener(this);
        productcomment.setOnClickListener(this);
        productImage.setOnClickListener(this);
        productNumTv.addTextChangedListener(mTextWatcher);
        Collection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    Collection.setText("已收藏");
                    requestCollection();

                } else {
                    Collection.setText("收藏");
                    requestDeleProduct();
                }
            }
        });

    }
    private void initData() {
        product = getIntent().getStringExtra("id");
        LogUtil.i(TAG, "id：" + product);

    }

    @Override
    //acticity生命周期，进入这个页面的时候调取接口
    public void onResume() {
        super.onResume();
        initRequest();

    }

    private void initRequest() {
        if (AppUtil.isNetworkAvailable(ProductDtailActivity.this)) {

            requestGetProduct();
        } else {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

    }
    TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // 判断输入数据是否超出库存数量
            if (!TextUtils.isEmpty(productSales)) {
                if (!TextUtils.isEmpty(productNumTv.getText().toString())) {
                    if (Integer.valueOf(productNumTv.getText().toString()) >= Integer
                            .valueOf(productSales)) {

                        productNumTv.setSelection(productNumTv.length());// 光标
                    } else {
                        productNumTv.setSelection(productNumTv.length());// 光标
                    }

                }

            }

        }

    };

//获取图片详情
    private void requestGetProduct() {
        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
       HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("ProductId", product);
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Product).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(ProductDtailActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "获取商品详情：" + response);
                        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取商品详情"))) {
                            ProderRequestModels model = JSON.parseObject(response, ProderRequestModels.class);
                            if (model != null && model.getResult() == 0) {
                                proderRequestModel = model.getData();
                                bannerLists = new ArrayList<ProderBanner>();
                                bannerLists = proderRequestModel.getProductAlbum();
                                // 图片轮播处理
                                for (ProderBanner banners : bannerLists) {
//                                    mDepthViews = getViews(bannerLists.size());
//                                    for (int i = 0; i < mDepthViews.size(); i++) {
//                                        RelativeLayout relativeLayout = (RelativeLayout) mDepthViews.get(i);
//                                        simpleDraweeView= (ImageView) relativeLayout.findViewById(R.id.mPlayImage);
//                                        simpleDraweeView.setScaleType(ImageView.ScaleType.FIT_XY);
//                                        Picasso.with(ProductDtailActivity.this).load(bannerLists.get(i).getOriginalAddress())
//                                                .placeholder(R.drawable.default_image)
//                                                .into(simpleDraweeView, new Callback() {
//                                                    @Override
//                                                    public void onSuccess() {
//                                                        loadingDialog.setVisibility(View.GONE);
//                                                        simpleDraweeView.setVisibility(View.VISIBLE);
//                                                        mDefaultBanner.setData(mDepthViews);
//                                                    }
//
//                                                    @Override
//                                                    public void onError() {
//                                                        loadingDialog.setVisibility(View.GONE);
//                                                        simpleDraweeView.setBackgroundResource(R.drawable.default_image);
//                                                    }
//                                                });
//                                    }
                                    loadData(mDefaultBanner, bannerLists.size());

                                    productname.setText(proderRequestModel.getProductInfo().getProductName());
                                    Sell.setText(proderRequestModel.getProductInfo().getShopPrice());
                                    Market.setText(proderRequestModel.getProductInfo().getMarketPrice());
                                    Sale.setText(proderRequestModel.getProductInfo().getSaleNum());
                                    Stock.setText(proderRequestModel.getProductInfo().getStock());
                                    productSales=proderRequestModel.getProductInfo().getStock();

                                    if (proderRequestModel.getProductInfo().isCollectioned() == true) {
                                        Collection.setChecked(proderRequestModel.getProductInfo().isCollectioned());
                                        Collection.setText("已收藏");
                                        id = proderRequestModel.getProductInfo().getCollectionRecordId();

                                    } else {

                                        id = "";
                                    }


                                }


                            }

                        } else {
                            ToastUtil.showShort(ProductDtailActivity.this, NetRequestUtil.requestsError(response, "获取商品详情"));

                        }
                    }

                    private void loadData(BGABanner banner, int size) {
                        banner.setAdapter(ProductDtailActivity.this);
                        banner.setData(bannerLists,null);
                    }

                });
    }

//    private List<View> getViews(int count) {
//        List<View> views = new ArrayList<>();
//            for (int i = 0; i < count; i++) {
//                LayoutInflater inflater = LayoutInflater.from(ProductDtailActivity.this);
//                View view = inflater.inflate(R.layout.play_view_itemi, null);
//                loadingDialog = (ProgressBar) view
//                        .findViewById(R.id.imagezoomdialog_progress);
//                simpleDraweeView = (ImageView) view.findViewById(R.id.mPlayImage);
//                views.add(view);
//            }
//            return views;
//
//    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(this, class1));

    }
    //添加收藏
    private void requestCollection() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone",AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
        params.put("ProductId", product);
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Collection).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(ProductDtailActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "收藏商品：" + response);
                        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                        if (model != null && model.getResult() == 0 || model.getResult() == 1) {
                            id = model.getData();
                            LogUtil.i(TAG, "收藏商品id：" + id);

                        } else {
                            Collection.setChecked(false);
                            Collection.setText("收藏");
                            ToastUtil.showShort(ProductDtailActivity.this, NetRequestUtil.requestsError(response, "收藏商品"));
                        }


                    }

                });
    }
//  取消收藏
private void requestDeleProduct() {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
    params.put("MobilePhone",AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
    params.put("ProductId", product);
    params.put("Id",id);
    params.put("Sign", FormatRequest.main(params));
    new OkHttpRequest.Builder()
            .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Collection).params(params)
            .post(new ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {

                    ToastUtil.showShort(ProductDtailActivity.this, "网络相应失败请稍后再试");
                }

                @Override
                public void onResponse(String response) {
                    LogUtil.i(TAG, "收藏商品：" + response);
                    mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    ProderRequestModels model = JSON.parseObject(response, ProderRequestModels.class);
                    if (model != null && model.getResult() == 0 || model.getResult() == 1) {


                    } else {
                        Collection.setChecked(false);
                        Collection.setText("收藏");
                        ToastUtil.showShort(ProductDtailActivity.this, NetRequestUtil.requestsError(response, "收藏商品"));
                    }


                }

            });


}

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.product_addShopcartBtn:
                if(AppApplication.getInstance().getSpUtil().isLogin()) {
                    hud = KProgressHUD.create(this)
                            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                            .setLabel("正在加载")
                            .setCancellable(true);
                    hud.show();
                    requestAddProduct();
                }else {
                    startActivity(new Intent(ProductDtailActivity.this, LoginActivity.class));
                }
                break;
            case R.id.productNumSub:
                if (TextUtils.isEmpty(productNumTv.getText().toString())) {

                    Snackbar.make(ShopcartBtn, "亲,商品至少买一件！", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (Integer.parseInt(productNumTv.getText().toString()) <= 1) {

                    Snackbar.make(ShopcartBtn, "亲,商品至少买一件！", Snackbar.LENGTH_SHORT).show();
                    productNumTv.setText("1");
                    productNumTv.setSelection(productNumTv.length());// 光标
                    return;
                }
                productNumTv.setText(String.valueOf(Integer.parseInt(productNumTv
                        .getText().toString()) - 1));
                productNumTv.setSelection(productNumTv.length());// 光标
                break;
            case R.id.productNumAdd:
                if (Integer.parseInt(productNumTv.getText().toString()) >= Integer
                        .parseInt(productSales)) {
                    Snackbar.make(ShopcartBtn, "该商品库存不足！", Snackbar.LENGTH_SHORT).show();

                    return;
                }
                productNumTv.setText(String.valueOf(Integer.parseInt(productNumTv
                        .getText().toString()) + 1));

                break;
            case R.id.product_toBuyBtn:
                if(AppApplication.getInstance().getSpUtil().isLogin()) {
                    redirectToOrderCenter();
                }else {
                    startActivity(new Intent(ProductDtailActivity.this, LoginActivity.class));
                }
                break;
            case R.id.productComment:
                Intent intent = new Intent(ProductDtailActivity.this,
                        ProductCommentActivity.class);
               intent.putExtra("id",product);
                startActivity(intent);
                break;
            case R.id.productImageTextRL:
                // ShowToast("图文详情");
                Intent mIntent = new Intent(ProductDtailActivity.this, BrowserActivity.class);
                // 判断商品图文详情是否为空
                String urlStr = "";
                if (TextUtils.isEmpty(proderRequestModel.getProductInfo().getContentTemplate())) {
                    urlStr = "";
                } else {
                    urlStr = "" + proderRequestModel.getProductInfo().getContentTemplate() + "";
                }

                mIntent.putExtra("url", urlStr);
                mIntent.putExtra("key", BrowserActivity.PRODUCTDETAIL);
                startActivity(mIntent);
                break;
        }

    }
    private void requestAddProduct() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone",AppApplication.getInstance().getSpUtil().getUSER_mobile().toString());
        params.put("ProductId", product);
        params.put("Quantity",productNumTv.getText().toString().trim() );
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Shoppingcar).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(ProductDtailActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "添加购物车：" + response);
                        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        ProderRequestModels model = JSON.parseObject(response, ProderRequestModels.class);
                        if (model != null && model.getResult() == 0 ) {
                            hud.dismiss();
                            Snackbar.make(ShopcartBtn, R.string.tips_shoping, Snackbar.LENGTH_SHORT).show();

                        } else {
                            hud.dismiss();
                            ToastUtil.showShort(ProductDtailActivity.this, NetRequestUtil.requestsError(response, "收藏商品"));
                        }


                    }

                });
    }
    /**
     * 跳转到结算中心
     */
    private void redirectToOrderCenter() {
        ArrayList<ShopModel> items = new ArrayList<ShopModel>();
        ShopModel item = new ShopModel();
        item.setQuantity(productNumTv.getText().toString());
        item.setPrice(proderRequestModel.getProductInfo().getShopPrice());
        item.setProductId(proderRequestModel.getProductInfo().getProductId());
        item.setProductImage(proderRequestModel.getProductAlbum().get(0).getOriginalAddress());
        item.setProductName(proderRequestModel.getProductInfo().getProductName());
        items.add(item);
        LogUtil.i(TAG, "改造后的数据为：" + proderRequestModel.getProductInfo().getProductName()
                + ",产品数量：" + productNumTv.getText().toString().trim() + ",产品价格："
                + proderRequestModel.getProductInfo().getShopPrice());

        if (items.size() > 0) {
            ShoppingCartBean bean = new ShoppingCartBean();
            bean.setProductList(items);

            Intent intent = new Intent(ProductDtailActivity.this,
                    SubmitOrder.class);
            Bundle data = new Bundle();
            data.putSerializable("data", bean);
            data.putString("type","1");
            intent.putExtras(data);
            startActivity(intent);

        }
    }

    @Override
    public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
        Glide.with(ProductDtailActivity.this)
                .load(bannerLists.get(position).getOriginalAddress())
                .placeholder(R.drawable.image_loader_small)
                .error(R.drawable.image_fail)
                .into((ImageView) view);
    }
}
